package com.example.cato_message_jms.jms;

import com.example.cato_entity.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.MessagePostProcessor;
import org.springframework.stereotype.Service;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

@Service
public class JmsOrderMessagingService implements OrderMessagingService {

    private JmsTemplate jmsTemplate;

    private Destination orderQueue;

    @Autowired
    public JmsOrderMessagingService(JmsTemplate jmsTemplate, Destination orderQueue) {
        this.jmsTemplate = jmsTemplate;
        this.orderQueue = orderQueue;
    }

    @Override
    public void sendOrder(Order order) {
        jmsTemplate.convertAndSend(orderQueue, order, this::addOrderResource);
    }


    private Message addOrderResource(Message message) throws JMSException {
        message.setStringProperty("X_ORDER_SOURCE", "WEB");
        return message;
    }


    //convertAndSend（）方法，因为无法访问Message，因为他在底层,第三个参数传入MessagePostProcessor
//    @Override
//    public void sendOrder(Order order) {
//        jmsTemplate.convertAndSend(orderQueue, order, new MessagePostProcessor() {
//            @Override
//            public Message postProcessMessage(Message message) throws JMSException {
//                message.setStringProperty("X_ORDER_SOURCE","WEB");  //自定义头部，让他携带消息的来源
//                return message;
//            }
//        });
//    }

//    @Override
//    public void sendOrder(Order order) {
//       jmsTemplate.send(orderQueue, new MessageCreator() {
//           @Override
//           public Message createMessage(Session session) throws JMSException {
//               Message message = session.createObjectMessage(order);
//               message.setStringProperty("X_ORDER_SOURCE","WEB");
//               return message;
//           }
//       });
//    }

//    @Override
//    public void sendOrder(Order order) {
//        jmsTemplate.convertAndSend(orderQueue,order); //简化了，不在需要MessageCreator
//    }

//    @Override
//    public void sendOrder(Order order) {
//        jmsTemplate.send(orderQueue,session -> session.createObjectMessage(order));//通过createObjectMessage将对象转换成消息
//    }

//    @Override //通过lambda表达式,目的地写在yml文件
//    public void sendOrder(Order order) {
//        jmsTemplate.send(session -> session.createObjectMessage(order));
//    }

//    @Override
//    public void sendOrder(Order order) {
//        jmsTemplate.send(new MessageCreator() {
//            @Override
//            public Message createMessage(Session session) throws JMSException {
//                return session.createObjectMessage(order);
//            }
//        });
//    }
}
